package com.leoman.controller;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.entity.Area;
import com.leoman.entity.Image;
import com.leoman.entity.Type;
import com.leoman.entity.User;
import com.leoman.entity.vo.WxContactVo;
import com.leoman.entity.vo.WxUserVo;
import com.leoman.service.*;
import com.leoman.utils.BeanUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 基础控制层
 * Created by 涂奕恒 on 2015/7/29.
 */
@Controller
@RequestMapping(value = "admin")
public class IndexController extends CommonController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private UploadImageService uploadImageService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private AreaService areaService;

    @RequestMapping(value = "/login")
    public String login(String error,
                        ModelMap model) {
        if (StringUtils.isNotBlank(error)) {
            model.addAttribute("error", error);
        }
        return "登录";
    }

    @RequestMapping(value = "/login/check")
    public String checkLogin(HttpServletRequest request,
                             String account,
                             String password,
                             ModelMap model) {
        Boolean success = loginService.login(request, account, password);

        if (success) {
            return "redirect:/admin/dashboard";
        }
        model.addAttribute("error", "用户名或密码错误!");
        return "redirect:/admin/login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        loginService.logOut(request, Constant.MEMBER_TYPE_GLOBLE);
        return "登录";
    }

    @RequestMapping(value = "/")
    public String index() {
        return "redirect:/admin/dashboard";
    }

    @RequestMapping(value = "/dashboard")
    public String dashboard() {
        return "控制面板";
    }

    /**
     * 上传缓存图片
     *
     * @return 图片
     */
    @RequestMapping("/addTempImage")
    @ResponseBody
    public Image addTempImage(MultipartRequest multipartRequest) {
        Image image = new Image();

        try {
            MultipartFile multipartFile = multipartRequest.getFile("tempImage");

            // 验证图片格式
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return image;
            }

            String url = uploadImageService.uploadFile(multipartFile);
            image.setUrl(url);

            imageService.create(image);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return image;
    }

    @RequestMapping("/typeList")
    @ResponseBody
    public List<Type> typeList() {
        return typeService.findList();
    }

    @RequestMapping("/areaList")
    @ResponseBody
    public List<Area> areaList() {
        return areaService.findParentList();
    }

    @RequestMapping("/areaListPlus")
    @ResponseBody
    public List<Area> areaListPlus(Integer areaId) {
        return areaService.findList(areaId);
    }

    @RequestMapping("/sectionList")
    @ResponseBody
    public List<WxContactVo> sectionList(HttpServletRequest request) {
        return getContactList(request);
    }

    @RequestMapping("/memberList")
    @ResponseBody
    public List<WxUserVo> memberList(HttpServletRequest request, Integer contactId) {
        try {
            for (WxContactVo wxContactVo : getContactList(request)) {
                if (wxContactVo.getId().equals(contactId)) {
                    return wxContactVo.getUserList();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping("/contactList")
    public String contactList(HttpServletRequest request, ModelMap modelMap) {
        try {
            modelMap.addAttribute("wxContactVoList", getContactList(request));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "weixin/contacts";
    }

    @RequestMapping("/contactDetail")
    public String contactDetail(HttpServletRequest request, Integer id, ModelMap modelMap) {
        for (WxContactVo wxContactVo : getContactList(request)) {
            if (wxContactVo.getId().equals(id)) {
                modelMap.addAttribute("contactDetail", wxContactVo);
            }
        }

        return "weixin/contacts-detail";
    }

    /**
     * 获取部门信息
     */
    @SuppressWarnings("unchecked")
    public static List<WxContactVo> getContactList(HttpServletRequest request) {
        List<WxContactVo> wxContactVoList = new ArrayList<>();
        List<WxUserVo> wxUserVoList;
        WxContactVo wxContactVo;
        WxUserVo wxUserVo;

        try {
            WxCpService wxCpService;

            // 类型：1=协和齿环，2=泛洲中越
//            System.out.println("企业号名称：武汉协和齿环");
//            wxCpService = (WxCpService) BeanUtil.getBean("wxCpService1");

             System.out.println("企业号名称：武汉泛洲中越合金");
             wxCpService = (WxCpService) BeanUtil.getBean("wxCpService");

            List<WxCpDepart> list = wxCpService.departGet();

            for (WxCpDepart wxCpDepart : list) {
                if (wxCpDepart.getParentId().equals(0)) {
                    continue;
                }

                wxContactVo = new WxContactVo();
                wxContactVo.setId(wxCpDepart.getId());
                wxContactVo.setName(wxCpDepart.getName());

                wxUserVoList = new ArrayList<>();

                List<WxCpUser> wxCpUsers = wxCpService.departGetUsers(wxCpDepart.getId(), null, 0);
                for (WxCpUser wxCpUser : wxCpUsers) {
                    wxUserVo = new WxUserVo();
                    wxUserVo.setId(wxCpUser.getUserId());
                    wxUserVo.setName(wxCpUser.getName());

                    wxUserVoList.add(wxUserVo);
                }

                wxContactVo.setUserList(wxUserVoList);

                wxContactVoList.add(wxContactVo);
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        request.getSession().setAttribute("sessionWxContactVoList", wxContactVoList);

        return wxContactVoList;
    }
}
